package logic

import (
	"context"
	"fmt"
	"zg1/weipinhui/models/cache"
	"zg1/weipinhui/models/mysql"
	"zg1/weipinhui/pkg"

	"zg1/weipinhui/wphrpc/internal/svc"
	"zg1/weipinhui/wphrpc/wphrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterLogic) Register(in *wphrpc.RegisterRequest) (*wphrpc.RegisterResponse, error) {
	// todo: add your logic here and delete this line
	findWph := mysql.User{}
	mysql.DB.Where("account=?", in.Account).Find(&findWph)

	if findWph.ID != 0 {
		return nil, fmt.Errorf("用户已存在")
	}

	wph := mysql.User{
		Account:  in.Account,
		Tel:      in.Tel,
		Password: pkg.Md5(in.Password),
	}

	cha, err := cache.Rdb.Get(l.ctx, "captcha"+in.Account).Result()
	if err != nil {
		return nil, err
	}

	if cha != in.ChaCode {
		return nil, fmt.Errorf("图形验证码错误")
	}

	sms, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.Tel).Result()
	if sms != in.SmsCode {
		return nil, fmt.Errorf("短信验证码错误")
	}

	mysql.DB.Create(&wph)

	return &wphrpc.RegisterResponse{
		Id: int64(wph.ID),
	}, nil
}
